package work.huangxin.share.controller.sechand;


import com.github.pagehelper.PageInfo;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import work.huangxin.share.domain.other.WXSessionModel;
import work.huangxin.share.domain.sechand.SechandBuyGoods;
import work.huangxin.share.globalException.MyException;
import work.huangxin.share.service.SechandBuyGoodsService;
import work.huangxin.share.service.impl.MinioSysFileServiceImpl;
import work.huangxin.share.util.RedisUtil;
import work.huangxin.share.util.ThreadLocalUtil;
import work.huangxin.share.util.status.BaseResponse;
import work.huangxin.share.util.status.CodeEnum;
import work.huangxin.share.util.status.ResponseData;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
* @author 钟声浩
* @date 2023/3/25 21:55
*/

@RestController
@RequestMapping("/wx/sechandBuyGoods")
public class SechandBuyGoodsController {

    @Autowired
    private SechandBuyGoodsService sechandBuyGoodsService;

    @Autowired
    private MinioSysFileServiceImpl minioSysFileService;
    @Autowired
    @Qualifier("fileThreadPool")
    private ThreadPoolExecutor fileThreadPool;
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 用户新增求购商品
     * @param files
     * @param
     * @param request
     * @return
     */
    @PostMapping("/saveBuyGoods")
    public BaseResponse saveBugGoodByUserId(
            @RequestPart("files") MultipartFile[] files,
            //@RequestParam("secHandGoods") String jsonStr,
            @RequestPart("secHandBuyGoods") SechandBuyGoods sechandBuyGoods,
            HttpServletRequest request) {
        WXSessionModel user = (WXSessionModel) request.getSession().getAttribute("user");
        Long userId = ThreadLocalUtil.get();
        WXSessionModel user1 = (WXSessionModel) redisUtil.get("user:" + userId);
        //SechandGoods sechandGoods = JSON.parseObject(jsonStr, SechandGoods.class);
        sechandBuyGoods.setUserId(Long.valueOf(user.getUserId()));
        //MultipartFile[] files = sechandGoods.getFiles();
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        CountDownLatch countDownLatch = new CountDownLatch(files.length);
        for (int i = 0; i < files.length; i++) {
            try {
                MultipartFile file = files[i];
                //TODO 使用CountDownLaunch或者ComplatableFuture或者Semaphore
                //来完成多线程的文件上传
                fileThreadPool.submit(() -> {
                    try {
                        String url = minioSysFileService.uploadFile(file);
                        list.add(url);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        //表示一个文件已经被完成
                        countDownLatch.countDown();
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        try {
            //阻塞直到所有的文件完成复制
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //统计每个文件的url
        String photoUrls = String.join(",", list);
        sechandBuyGoods.setBuyGoodsPhotos(photoUrls);
        sechandBuyGoodsService.insertSechandBuyGoods(sechandBuyGoods);
        return ResponseData.success(sechandBuyGoods);
    }

    /**
     *更新求购商品
     */

    @PutMapping("/updateBuyGoods")
    public BaseResponse updateBuyGoods(
            @RequestPart("files") MultipartFile[] files,
            //@RequestParam("secHandGoods") String jsonStr,
            @RequestPart("secHandBuyGoods") SechandBuyGoods sechandBuyGoods,
            HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //SechandGoods sechandGoods = JSON.parseObject(jsonStr, SechandGoods.class);
        minioSysFileService.deleteFiles(sechandBuyGoods.getBuyGoodsPhotos());
        //MultipartFile[] files = sechandGoods.getFiles();
        //线程安全
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        CountDownLatch countDownLatch = new CountDownLatch(files.length);
        for (int i = 0; i < files.length; i++) {
            try {
                MultipartFile file = files[i];
                //TODO 使用CountDownLaunch或者ComplatableFuture或者Semaphore
                //来完成多线程的文件上传
                fileThreadPool.submit(() -> {
                    try {
                        String url = minioSysFileService.uploadFile(file);
                        list.add(url);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        //表示一个文件已经被完成
                        countDownLatch.countDown();
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        try {
            //阻塞直到所有的文件完成复制
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //统计每个文件的url
        String photoUrls = String.join(",", list);
        sechandBuyGoods.setBuyGoodsPhotos(photoUrls);
        int isUpdate = sechandBuyGoodsService.updateSechandGoods(sechandBuyGoods);
        if (isUpdate <= 0) {
            return ResponseData.error(CodeEnum.BODY_NOT_MATCH);

        }
        return ResponseData.success();
    }


    /**
     * 分页展示所有求购商品的数据
     */
    @GetMapping("/getBuyGoodsPage")
    public BaseResponse getAllBuyGoods(@RequestParam Integer pageNum,
                                       @RequestParam Integer pageSize) {
        if (pageSize == 0){
            throw new MyException(BaseResponse.out(CodeEnum.BODY_NOT_MATCH),new Exception("输入有误"));
        }
        PageInfo<SechandBuyGoods> sechandBuyGoodsPageInfo =
                sechandBuyGoodsService.selectPageSechandBuyGoodsList(pageNum, pageSize);
        if (Objects.isNull(sechandBuyGoodsPageInfo)) {
            return ResponseData.out(CodeEnum.NOT_FOUND, "首页数据丢失");
        }
        return ResponseData.out(CodeEnum.SUCCESS, sechandBuyGoodsPageInfo);
    }

    /**
     * 用户查询自己发布的求购商品
     */
    @GetMapping("/getBuyGoodsByUser")
    public BaseResponse getBuyGoodsByUser(HttpServletRequest request) {
        WXSessionModel user = (WXSessionModel) request.getSession().getAttribute("user");
        Long userId = ThreadLocalUtil.get();
        WXSessionModel user1 = (WXSessionModel) redisUtil.get("user:" + userId);
        if (user.getUserId() < 0) {
            return ResponseData.error(403, "用户身份异常");
        }
        List<SechandBuyGoods> sechandBuyGoodsByUserId = sechandBuyGoodsService.selectSechandBuyGoodsByUserId(user.getUserId());
        if (Objects.isNull(sechandBuyGoodsByUserId)) {
            return ResponseData.out(CodeEnum.NOT_FOUND, "用户求购商品查询失败");
        }
        return ResponseData.success(sechandBuyGoodsByUserId);
    }

    /**
     * 查看求购商品详情
     */
    @GetMapping("/getBuyGoodsById/{id}")
    public BaseResponse getBuyGoodsById(@PathVariable("id") Integer id) {
        SechandBuyGoods sechandBuyGoods = sechandBuyGoodsService.selectSechandBuyGoodsById(id);
        if (Objects.isNull(sechandBuyGoods)) {
            return ResponseData.error(404, "请求商品非法");
        }
        return ResponseData.success(sechandBuyGoods);
    }

//    /**
//     * 更新自己求购商品的信息
//     */
//    @PutMapping("/updateBuyGoods")
//    public BaseResponse updateBuyGoodsById(@RequestBody SechandBuyGoods sechandBuyGoods,
//                                           HttpServletRequest request) {
//        //校验用户的userId是否一致
//        WXSessionModel user = (WXSessionModel) request.getSession().getAttribute("user");
//        Long userId = Long.valueOf(user.getUserId());
//        if (!(userId > 0 && userId.equals(sechandBuyGoods.getUserId()))) {
//            return ResponseData.out(CodeEnum.SIGNATURE_NOT_ALLOW, "您没有权限进行此操作");
//        }
//        int update = sechandBuyGoodsService.updateBuyGoods(sechandBuyGoods);
//        if (update <= 0) {
//            return ResponseData.out(CodeEnum.NOT_FOUND, "求购商品为更新成功");
//        }
//        return ResponseData.success();
//    }


    /**
     * 通过关键字搜索求购商品
     */
    @GetMapping("/getBuyGoodsByKeyWord")
    public BaseResponse getBuyGoodsByKeyWord(@RequestParam String keyword,
                                             @RequestParam Integer pageNum,
                                             @RequestParam Integer pageSize) {
        PageInfo<SechandBuyGoods> pageInfo = sechandBuyGoodsService.getBuyGoodsByKeyWord(keyword, pageNum, pageSize);
        return ResponseData.success(pageInfo);
    }

    /**
     * 删除求购商品
     */
    @DeleteMapping("/deleteBuyGoods")
    public BaseResponse deleteBuyGoods(@RequestParam Integer userId,
                                       @RequestParam Integer goodsId,
                                       HttpServletRequest request) {
        WXSessionModel user = (WXSessionModel)request.getSession().getAttribute("user");
        Long userId1 = ThreadLocalUtil.get();
        WXSessionModel user1 = (WXSessionModel) redisUtil.get("user:" + userId);
        if (!(user.getUserId() > 0 && user.getUserId().equals(userId))) {
            return ResponseData.out(CodeEnum.SIGNATURE_NOT_ALLOW);
        }
        int count = sechandBuyGoodsService.deleteBuyGoods(userId, goodsId);
        if(count <= 0) {
            return ResponseData.out(CodeEnum.NOT_FOUND, "未找到该商品");
        }
        return ResponseData.success();
    }

    /**
     * 下架求购商品
     */
    @PutMapping("/isBuied")
    public BaseResponse setBuyGoodsIsBuied(@RequestParam Integer goodsId,
                                           @RequestParam Integer userId,
                                           HttpServletRequest request) {
        //获取登录用户的id
        WXSessionModel user = (WXSessionModel)request.getSession().getAttribute("user");
        Long userId1 = ThreadLocalUtil.get();
        WXSessionModel user1 = (WXSessionModel) redisUtil.get("user:" + userId);
        if (!(user.getUserId() > 0 && user.getUserId().equals(userId))) {
            return ResponseData.out(CodeEnum.SIGNATURE_NOT_ALLOW);
        }
        int count = sechandBuyGoodsService.setBuyGoodsIsBuied(userId, goodsId);
        if (count <= 0) {
            return ResponseData.out(CodeEnum.NOT_FOUND, "该求购商品已经不存在");
        }
        return ResponseData.success();
    }
}
